package com.star.common.orm.typehandlers;

import com.star.common.orm.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Array;
import java.util.List;

@Slf4j
public class JsonStringTypeHandler<T> extends BaseStringTypeHandler<T> {
    private Class<?> componentType;
    private Object[] componentArray;

    public JsonStringTypeHandler() {
        Class<T> tClass = type();
        if (tClass.isArray()) {
            Class<Object[]> arrayClass = (Class<Object[]>) tClass;
            this.componentType = arrayClass.getComponentType();
            this.componentArray = (Object[]) Array.newInstance(componentType, 0);
        }
        log.info("### BASE-DATA : INIT {}, type: {} ###", this.getClass().getSimpleName(), type().getSimpleName());
    }

    @Override
    protected String convert(T obj) {
        return JsonUtils.toJson(obj);
    }

    @Override
    protected T parse(String json) {
        if (this.componentType != null) {
            List<?> list = JsonUtils.toList(json, this.componentType);
            if (list == null) return null;
            return (T) list.toArray(this.componentArray);
        }
        return JsonUtils.toObject(json, type());
    }

}
